<?php
namespace App\Logic\SalesReportLT;
use App\Models\Basics\ExchangeRate;
use App\Models\SalesReportLT\PaymentTNSummary as TPaymentTNSummary;
use App\Models\SalesReportLT\PaymentDetail as TPaymentDetail;
use Illuminate\Support\Facades\DB;
class PaymentNone
{
    public static function exePayment($date){
        ini_set('memory_limit', '200M');
        set_time_limit(0);
        try{
            $start = time();
            $start_memory = memory_get_usage();
            DB::beginTransaction();
            $headers = TPaymentTNSummary::headersField();
            $pd = TPaymentDetail::query()
                ->where('report_date',$date)
                ->selectRaw(self::_getSumFields($headers))
                ->groupBy(1)
                ->first();
            if($pd){
                $data = $pd->toArray();
                unset($data[0]);
                $rateOdds = ExchangeRate::getRateOddsToRMB('JPY',strtotime($date));
                $data['rate_odds'] = $rateOdds;
                TPaymentTNSummary::query()->updateOrCreate(
                    ['report_date' => $date],$data
                );
            }
            DB::commit();
            $end = time();
            $end_memory = memory_get_usage();
            print_r(($end - $start).'--------'.(($end_memory - $start_memory)/1024/1024));
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
        }
    }

    private static function _getSumFields($headers): string
    {
        $re = '';
        foreach ($headers as $field => $item){
            if($item['sumField']){
                $re .= 'sum('.$field.') as '.$field.',';
            }
        }
        return $re.'1';
    }
}
